#include "chessboard.h"

GtkWidget* create_chessboard() {
    GtkWidget *chessboard;
    GtkWidget *drawing_area;

    chessboard = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);

    drawing_area = gtk_drawing_area_new();
    gtk_widget_set_size_request(drawing_area, 400, 400);
    gtk_box_pack_start(GTK_BOX(chessboard), drawing_area, TRUE, TRUE, 0);

    g_signal_connect(drawing_area, "draw", G_CALLBACK(on_draw), NULL);

    return chessboard;
}

gboolean on_draw(GtkWidget *widget, cairo_t *cr, gpointer data) {
    int width = gtk_widget_get_allocated_width(widget);
    int height = gtk_widget_get_allocated_height(widget);
    int cell_size = 40;  // Size of each chessboard cell
    int board_size = 8 * cell_size;  // Size of the chessboard
    int margin = (width - board_size) / 2;  // Margin around the chessboard

    // Draw background
    cairo_set_source_rgb(cr, 1, 1, 1);  // White background
    cairo_paint(cr);

    // Draw chessboard
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if ((i + j) % 2 == 0) {
                cairo_set_source_rgb(cr, 1, 1, 1);  // White cell
            } else {
                cairo_set_source_rgb(cr, 0, 0, 0);  // Black cell
            }
            cairo_rectangle(cr, margin + i * cell_size, margin + j * cell_size, cell_size, cell_size);
            cairo_fill(cr);
        }
    }

    // Draw labels around the chessboard
    cairo_set_source_rgb(cr, 0, 0, 0);  // Black text
    cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
    cairo_set_font_size(cr, 12);

    // Left and right labels (abcdefgh)
    for (int i = 0; i < 8; i++) {
        short int label = 'a' + i;
        cairo_text_extents_t extents;
        cairo_text_extents(cr, (char*)&label, &extents);
        cairo_move_to(cr, margin + i * cell_size + cell_size / 2 - extents.width / 2, height - margin / 2 + extents.height / 2);
        cairo_show_text(cr, (char*)&label);
        cairo_move_to(cr, margin + i * cell_size + cell_size / 2 - extents.width / 2, margin / 2 - extents.height / 2);
        cairo_show_text(cr, (char*)&label);
    }

    // Top and bottom labels (12345678)
    for (int i = 0; i < 8; i++) {
        short int label = '1' + i;
        cairo_text_extents_t extents;
        cairo_text_extents(cr, (char*)&label, &extents);
        cairo_move_to(cr, margin / 2 - extents.width / 2, margin + i * cell_size + cell_size / 2 + extents.height / 2);
        cairo_show_text(cr, (char*)&label);
        cairo_move_to(cr, width - margin / 2 - extents.width / 2, margin + i * cell_size + cell_size / 2 + extents.height / 2);
        cairo_show_text(cr, (char*)&label);
    }

    return FALSE;
}